package com.coderlin.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.coderlin.pojo.Role;
import com.coderlin.pojo.User;
import com.coderlin.service.role.RoleService;
import com.coderlin.service.role.RoleServiceImpl;
import com.coderlin.service.user.UserService;
import com.coderlin.service.user.UserServiceImpl;
import com.coderlin.util.Constants;
import com.coderlin.util.PageSupport;
import org.junit.platform.commons.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <Description> <br>
 *
 * @author Coder_Lin<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2021/03/13 13:27 <br>
 * @see com.coderlin.servlet.user <br>
 */

/**
 * 实现Servlet复用
 * */
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method != null && method.equals("savepwd")){
            this.updatePwd(req,resp);
        }else if(method != null && method.equals("pwdmodify")){
            this.pwdModify(req,resp);
        }else if(method != null && method.equals("query")){
            this.query(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        String newpassword = req.getParameter("newpassword");
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        boolean flag = false;
        if(o!=null && StringUtils.isNotBlank(newpassword)){
            try{
                UserServiceImpl userService = new UserServiceImpl();
                flag = userService.updatePwd(((User) o).getId(), newpassword);
                if(flag){   // 密码修改成功
                    req.setAttribute("message","密码修改成功，请退出，使用新密码登录。");
                    req.getSession().removeAttribute(Constants.USER_SESSION);
                }else{
                    req.setAttribute("message","密码修改失败");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            req.setAttribute("message","新密码有误");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //验证旧密码，session中有用户密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        // 万能Map:结果集
        Map<String,String> resultMap = new HashMap<String,String>();
        if( o == null){                     //session失效了,session过期了
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isBlank("oldpassword")){  // 输入的密码为空
            resultMap.put("result","error");
        }else{
            String userPassword = ((User) o).getUserPassword();     // session中用户的密码
            if(oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            // JSONArray 阿里巴巴的JSON工具类, 转换格式
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**查询用户列表
     * */
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //查询数据
        /**
         * @param queryName,queryRole,pageIndex
         * */
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        System.out.println(queryUserName);
        System.out.println(temp);
        System.out.println(pageIndex);
        int queryUserRole = 0;
        //获取用户列表
        UserService userService = new UserServiceImpl();
        List<User> userList = null;
        //pagesize
        int currentPageNo = 1;
        int pageSize = 5;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);
        }
        if(pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        //获取用户总数（分页、上一页、下一页）
        int totalCount = userService.getUserCount(queryUserName,queryUserRole);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setTotalCount(totalCount);
        //这里的setTotalCount已经成功计算出了totalPageCount

        //控制首页和尾页
        int totalPageCount = pageSupport.getTotalPageCount();
        if(currentPageNo<1){
            currentPageNo = 1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo = totalPageCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);

        //获取角色列表
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        //将参数回传
        req.setAttribute("userList",userList);
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
